import pymysql
from pymysql.cursors import DictCursor
from datetime import datetime, timedelta
from typing import Dict, Any, List, Optional


def parse_datetime(time_str: str) -> Optional[datetime]:
    """解析ISO格式时间字符串为datetime对象"""
    try:
        return datetime.fromisoformat(time_str.replace('Z', '+00:00'))
    except Exception:
        return None


def query_logs_for_anomaly(anomaly: Dict[str, Any], db_config: Dict[str, Any]) -> Dict[str, List[Dict[str, Any]]]:
    """
    根据异常的start_time和duration，查询三个日志表在该时间段内的所有日志。
    返回：{'system_logs': [...], 'security_logs': [...], 'application_logs': [...]}。
    """
    start_time = anomaly.get('start_time')
    duration = anomaly.get('duration')
    if not start_time or duration is None:
        return {'system_logs': [], 'security_logs': [], 'application_logs': []}
    try:
        duration = int(duration)
    except Exception:
        return {'system_logs': [], 'security_logs': [], 'application_logs': []}
    start = parse_datetime(start_time)
    if not start:
        return {'system_logs': [], 'security_logs': [], 'application_logs': []}
    end = start + timedelta(seconds=duration)
    
    conn = None
    try:
        conn = pymysql.connect(
            host=db_config.get('host', 'localhost'),
            port=db_config.get('port', 3306),
            user=db_config.get('user', 'root'),
            password=db_config.get('password', ''),
            database=db_config.get('database', ''),
            charset='utf8mb4',
            cursorclass=DictCursor
        )
        system_logs = _query_table(conn, 'system_logs', start, end)
        security_logs = _query_table(conn, 'security_logs', start, end)
        application_logs = _query_table(conn, 'application_logs', start, end)
        return {
            'system_logs': system_logs,
            'security_logs': security_logs,
            'application_logs': application_logs
        }
    except Exception as e:
        return {'system_logs': [], 'security_logs': [], 'application_logs': []}
    finally:
        if conn:
            conn.close()

def _query_table(conn, table: str, start: datetime, end: datetime) -> List[Dict[str, Any]]:
    """查询指定表在时间段内的所有日志，按timestamp排序"""
    query = f"SELECT * FROM {table} WHERE timestamp BETWEEN %s AND %s ORDER BY timestamp"
    try:
        with conn.cursor() as cursor:
            cursor.execute(query, (start, end))
            return list(cursor.fetchall())
    except Exception:
        return []

def batch_query_logs_for_anomalies(anomalies: List[Dict[str, Any]], db_config: Dict[str, Any]) -> Dict[str, Dict[str, List[Dict[str, Any]]]]:
    """
    批量查询多个异常的日志，返回{anomaly_id: {'system_logs': ..., ...}}
    """
    results = {}
    for anomaly in anomalies:
        anomaly_id = anomaly.get('id', 'unknown')
        results[anomaly_id] = query_logs_for_anomaly(anomaly, db_config)
    return results 